package com.demo2do.fms.admin.web.controller.supplier.management;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.supplier.DriverSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.supplier.DriverService;
import com.demo2do.fms.admin.service.supplier.VehicleDriverRelationService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.driver.Driver;
import com.demo2do.fms.entity.driver.DriverAuditStatus;

/**
 *
 * @author Ark
 *
 */
@Controller
@RequestMapping("/relation-drivers")
@MenuSetting("menu-supplier")
public class DriverVeicleRelationController {
    
    private static final Logger logger = LoggerFactory.getLogger(DriverVeicleRelationController.class);
    
    @Autowired
    private DriverService driverService;
    
    @Autowired
    private VehicleDriverRelationService relationService;
    
    /**
     * 司机列表
     * 
     * @param bind
     * @param login
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-driver-vehicle-relation")
    public ModelAndView list(@RequestParam(name = "bind", required = false, defaultValue = "false") boolean bind,
                             @Secure Login login,
                             HttpServletRequest request,
                             Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-driver-list");
        modelAndView.addObject("bind", bind);
        
        int totals = driverService.count(login, DriverAuditStatus.QUALIFIED, bind);
        if (totals > 0) {
            
            List<Driver> drivers = driverService.list(login, DriverAuditStatus.QUALIFIED, bind, page.with(totals));
            
            modelAndView.addObject("drivers", drivers);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询
     * 
     * @param bind
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("bind") boolean bind) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-driver-search");
        
        modelAndView.addObject("bind", bind);
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询
     * 
     * @param driverSearch
     * @param login
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-driver-vehicle-relation")
    public ModelAndView onSearch(DriverSearch driverSearch, @Secure Login login,
                                 HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-driver-list");
        modelAndView.addObject("bind", driverSearch.getBind());
        
        if (login.isSupplier()) {
            driverSearch.setSupplierId(login.getSupplierId());
        }
        driverSearch.setStatus(DriverAuditStatus.QUALIFIED);
        
        int totals = driverService.count(driverSearch);
        if (totals > 0) {
            
            List<Driver> drivers = driverService.list(driverSearch, page.with(totals));
            
            modelAndView.addObject("drivers", drivers);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 创建绑定 - panel
     * 
     * @param driverId
     * @return
     */
    @RequestMapping(value = "/{driverId}/create", method = RequestMethod.GET)
    @MenuSetting("submenu-driver-vehicle-relation")
    public ModelAndView create(@PathVariable("driverId") Long driverId) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-create");
        
        Driver driver = driverService.load(driverId);
        modelAndView.addObject("driver", driver);
        
        return modelAndView;
        
    }
    
    /**
     * @param driverId
     * @param vehicleId
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{driverId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onCreate(@PathVariable("driverId") Long driverId,
                                             @RequestParam("vehicleId") Long vehicleId,
                                             @Secure(property = "id") Long operator) {

        HttpResult httpResult = new HttpResult();
        
        try {

            Driver driver = driverService.load(driverId);
            relationService.create(driver, vehicleId, operator);
            
            httpResult.success().message("绑定成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("绑定失败！" + e.getMessage());
            logger.error("onCreate() - bind fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * 更新绑定 - panel
     * 
     * @param driverId
     * @return
     */
    @RequestMapping(value = "/{driverId}/edit", method = RequestMethod.GET)
    @MenuSetting("submenu-driver-vehicle-relation")
    public ModelAndView edit(@PathVariable("driverId") Long driverId) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-edit");
        
        Driver driver = driverService.load(driverId);
        modelAndView.addObject("driver", driver);
        
        return modelAndView;
        
    }
    
    /**
     * 更新绑定
     * 
     * @param driverId
     * @param vehicleId
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{driverId}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onEdit(@PathVariable("driverId") Long driverId,
                                           @RequestParam("vehicleId") Long vehicleId,
                                           @Secure(property = "id") Long operator) {

        HttpResult httpResult = new HttpResult();
        
        try {

            Driver driver = driverService.load(driverId);
            relationService.edit(driver, vehicleId, operator);
            
            httpResult.success().message("绑定成功");
            
        } catch (Exception e) {
            httpResult.fail("500").message("绑定失败");
            logger.error("onBind() - bind fail, exception = [{}]", e);
        }
        
        return httpResult;
        
    }
    
    /**
     * 解除绑定
     * 
     * @param driverId
     * @return
     */
    @RequestMapping(value = "/{driverId}/unbind", method = RequestMethod.GET)
    public ModelAndView unbind(@PathVariable("driverId") Long driverId) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/management/relation/relation-unbind");
        
        modelAndView.addObject("driverId", driverId);
        
        return modelAndView;
        
    }
    
    /**
     * 解除绑定
     * 
     * @param driverId
     * @param login
     * @return
     */
    @RequestMapping(value = "/{driverId}/unbind", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onUnbind(@PathVariable("driverId") Long driverId,
                                             @Secure Login login) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            Driver driver = driverService.load(driverId);
            relationService.unbind(driver, login);
            
            httpResult.success().message("解除绑定成功");
            
        } catch (Exception e) {
            
            httpResult.fail("500").message("解除绑定失败," + e.getMessage());
            logger.error("#onUnbind() - unbind fail, exception = [{}]", e);
            
        }
        
        return httpResult;
        
    }
        
}
